<template>
  <div class="good-add">
    <el-steps :active="active" finish-status="success">
      <el-step title="步骤 1" description="基本信息"></el-step>
      <el-step title="步骤 2" description="商品图片"></el-step>
      <el-step title="步骤 3" description="商品描述"></el-step>
    </el-steps>
    <el-tabs v-model="activeTab" tab-position="left" @tab-click="handleClick" class="nav">
      <el-tab-pane label="基本信息" name="0">
        <el-form :model="goods" status-icon label-width="80px" ref="goods" :rules="rules">
          <el-form-item label="商品名称"  prop="goods_name">
            <el-input v-model="goods.goods_name" autocomplete="off" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="商品价格"  prop="goods_price">
            <el-input v-model.number="goods.goods_price" autocomplete="off" placeholder="请输入商品价格"></el-input>
          </el-form-item>
          <el-form-item label="商品重量"  prop="goods_weight">
            <el-input v-model.number="goods.goods_weight" autocomplete="off" placeholder="请输入商品重量"></el-input>
          </el-form-item>
          <el-form-item label="商品数量"  prop="goods_number">
            <el-input v-model.number="goods.goods_number" autocomplete="off" placeholder="请输入商品数量"></el-input>
          </el-form-item>
          <el-form-item label="商品分类"  prop="goods_cat">
            <div class="block">
              <el-cascader
              v-model="goods.goods_cat"
              :props="{label: 'cat_name', value: 'cat_id'}"
              :options="categories"
              @change="getCatId">
              </el-cascader>
            </div>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="next">下一步</el-button>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="1">
        <el-upload
          action="http://localhost:8888/api/private/v1/upload"
          list-type="picture-card"
          multiple
          name="file"
          :headers="headers"
          :on-success="successHandle">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
              <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <el-button type="primary" @click="next" style="margin-top:20px">下一步</el-button>
      </el-tab-pane>
      <el-tab-pane label="商品描述" name="2">
        <quill-editor v-model="goods.goods_introduce"></quill-editor>
        <el-button type="primary" @click="addGoods">添加</el-button>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data () {
    return {
      active: 0,
      activeTab: '',
      goods: {
        goods_name: '',
        goods_cat: '',
        goods_price: null,
        goods_number: null,
        goods_weight: null,
        goods_introduce: '',
        pics: []
      },
      categories: [],
      rules: {
        goods_name: [{ required: true, message: '商品名称不能为空', trigger: ['blur', 'change'] }],
        goods_cat: [{ required: true, message: '商品分类不能为空', trigger: ['blur', 'change'] }],
        goods_price: [
          { required: true, message: '商品价格不能为空', trigger: ['blur', 'change'] },
          { type: 'number', message: '商品价格应为数字', trigger: ['blur', 'change'] }
        ],
        goods_number: [
          { required: true, message: '商品数量不能为空', trigger: ['blur', 'change'] },
          { type: 'number', message: '商品数量应为数字', trigger: ['blur', 'change'] }
        ],
        goods_weight: [
          { required: true, message: '商品重量不能为空', trigger: ['blur', 'change'] },
          { type: 'number', message: '商品重量应为数字', trigger: ['blur', 'change'] }
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      headers: { Authorization: localStorage.getItem('token') },
      fileList: []
    }
  },
  methods: {
    handleClick (active) {
      this.active = Number(active.name)
    },
    getCatId (value) {
      // console.log(value)
      this.goods.goods_cat = value
    },
    next () {
      this.active++
      this.activeTab = this.active.toString()
      // this.$refs['goods'].validate(isPass => {
      //   console.log(isPass)
      // })
    },
    handleRemove (file, fileList) {
      const filePath = file.response.data.tmp_path
      this.goods.pics = this.goods.pics.filter(item => item.pic !== filePath)
      const index = this.fileList.findIndex(item => item.uid === file.uid)
      this.fileList.splice(index, 1)
    },
    successHandle (response, file, fileList) {
      this.goods.pics.push({ pic: response.data.tmp_path })
      this.fileList = fileList
    },
    handlePreview (file) {
      console.log('file', file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    async addGoods () {
      this.active = 3
      // console.log(this.goods)
      const { id } = this.$route.query
      if (id) {
        let { meta } = await this.$axios.put(`goods/${id}`, {
          goods_name: this.goods.goods_name,
          goods_cat: this.goods.goods_cat.join(),
          goods_price: this.goods.goods_price + '',
          goods_number: this.goods.goods_number + '',
          goods_weight: this.goods.goods_weight + '',
          goods_introduce: this.goods.goods_introduce,
          pics: this.goods.pics
        })
        if (meta.status !== 201) this.$message.error('修改商品失败')
        this.$message.success(meta.msg)
        this.$router.push('/goods')
        return
      }
      let res = await this.$axios.post('goods', {
        goods_name: this.goods.goods_name,
        goods_cat: this.goods.goods_cat.join(),
        goods_price: this.goods.goods_price + '',
        goods_number: this.goods.goods_number + '',
        goods_weight: this.goods.goods_weight + '',
        goods_introduce: this.goods.goods_introduce,
        pics: this.goods.pics
      })
      // console.log('resssss', res)
      let { meta } = res
      if (meta.status !== 201) this.$message.error('商品创建失败')
      this.$message.success(meta.msg)
      this.$router.push('/goods')
      this.getGoods()
    },
    async getGoods () {
      let res = await this.$axios.get('categories', { type: 3 })
      // console.log(res)
      this.categories = res.data
    }
  },
  async created () {
    // console.log(this.$route.query)
    const { id } = this.$route.query
    this.getGoods()
    if (id) {
      let res = await this.$axios.get(`goods/${id}`)
      // console.log(res)
      this.goods.goods_name = res.data.goods_name
      this.goods.goods_price = res.data.goods_price
      this.goods.goods_number = res.data.goods_number
      this.goods.goods_weight = res.data.goods_weight
      this.goods.goods_cat = [res.data.cat_one_id, res.data.cat_two_id, res.data.cat_three_id]
      // this.goods.pics = [{ pic: `http://localhost:8888/${res.data.pics_sma}` }]
      this.goods.goods_introduce = res.data.goods_introduce
    }
  }
}
</script>

<style lang="scss" scoped>
  .nav{
    margin-top: 20px
  }
  // 由于模板中的样式只能作用域表层组件，而组件中的HTML样式无法被应用上去
  // 方式一：
  // .quill-editor也可以另外写到新的style标签中，此style不写scope
  // 方式二：
  // 加上 ::v-deep前缀
  .quill-editor {
  background-color: #fff;
  margin-bottom: 20px;
  ::v-deep .ql-editor {
      min-height: 300px;
    }
  }
</style>
